<?php
/* 统一的服务器返回消息格式:
 * - code: 状态码（0表示成功，非0表示失败）
 * - status: 状态描述（如"success", "error"等）
 * - message: 详细消息
 * - data: 主要返回数据
 * - error: 错误详情（只有在error状态时才包含）
 * - meta: 元数据（如分页信息等，可选）
 */

class TaskSync extends CI_Controller {

    var $_login_userid;
    
    function __construct()
    {
        parent::__construct();
        $this->_login_userid = $this->get_login_userid();
        $this->load->database();
    }
    
    //获得当前登录的用户id
    private function get_login_userid()
    {
        $this->load->library('tank_auth');
        $this->lang->load('tank_auth');
        if ($this->tank_auth->is_logged_in()) {
            return $this->tank_auth->get_user_id();
        } else {
            return 0;
        }
    }

    //将数组转换成json，并输出
    private function array_to_json($array)
    {
        $json_string = json_encode($array);
        echo $json_string;
    }

    // 生成标准响应格式
    private function create_response($code = 0, $status = 'success', $message = '', $data = null, $error = null, $meta = null)
    {
        $response = array(
            'code' => $code,
            'status' => $status,
            'message' => $message,
            'data' => $data
        );
        
        if ($error !== null) {
            $response['error'] = $error;
        }
        
        if ($meta !== null) {
            $response['meta'] = $meta;
        }
        
        return $response;
    }

    public function getall($rand=0, $workarea=0)
    {
        try {
            if($this->_login_userid){
                $this->db->where('tid', NULL);
                $this->db->where('uid', $this->_login_userid);
            } else {
                $this->db->where('uid', 5);
            }
            
            if($workarea || isset($_POST['workarea'])){
                $this->db->where('areaid', $workarea);
            }

            $this->db->where('archive !=', '1'); //默认只取得所有未归档的任务
            $this->db->order_by('sort desc, parent asc');
            
            $query = $this->db->get('task');
            
            if ($query->num_rows() > 0) {
                $tasks = $query->result_array();
                $response = $this->create_response(0, 'success', '查询成功', $tasks, null, array('total' => count($tasks)));
            } else {
                $response = $this->create_response(1, 'nofound', '未找到任务', array());
            }
        } catch (Exception $e) {
            $response = $this->create_response(500, 'error', '查询任务时发生错误', null, array(
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ));
        }
        
        $this->array_to_json($response);
    }

    public function getChanged()
    {
        try {
            $since = $this->input->get_post('since');
            $request_deviceId = $this->input->get_post('deviceId');
            
            if (empty($since)) {
                $response = $this->create_response(400, 'error', '没有指定时间参数', null);
            } else {
                $this->db->where("lastupdate > '".$since."'");
                $this->db->where('sync', 1);
                if($request_deviceId){
                     // 修复：正确处理NULL值的情况
                    $this->db->where("(updated_device IS NULL OR updated_device <> '" . $this->db->escape_str($request_deviceId) . "')");
                }
                $query = $this->db->get('task');
                
                if ($query->num_rows() > 0) {
                    $tasks = $query->result_array();
                    $response = $this->create_response(0, 'success', '查询成功', array('tasks' => $tasks), null, array('total' => count($tasks)));
                } else {
                    $response = $this->create_response(1, 'nofound', '未找到更新的任务', array('tasks' => array()));
                }
            }
        } catch (Exception $e) {
            $response = $this->create_response(500, 'error', '查询变更任务时发生错误', null, array(
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ));
        }
        
        $this->array_to_json($response);
    }

    public function batchUpdate()
    {
        try {
            if (empty($_POST['tasks'])) {
                $response = $this->create_response(400, 'error', '没有指定任务数据', null);
            } else {
                $tasks = $_POST['tasks'];
                $updated_count = 0;
                $inserted_count = 0;
                $errors = array();
                
                foreach ($tasks as $task) {
                    // 定义需要检查的字段数组
                    $fieldsToCheck = ['start_date', 'end_date', 'internal_link', 'parent', 
                                     'gid', 'tid', 'icon', 'deleted', 'updated_device', 'areaid',
                                     'grandfather', 'num', 'haschild', 'allday'];

                    // 遍历数组，将空字符串转换为null
                    foreach ($fieldsToCheck as $field) {
                        if (isset($task[$field]) && $task[$field] === '') {
                            $task[$field] = null;
                        }
                    }
                    
                    try {
                        // 检查任务是否存在
                        $this->db->where('id', $task['id']);
                        $query = $this->db->get('task');
                        
                        if ($query->num_rows() > 0) {
                            // 任务存在，执行更新
                            $this->db->where('id', $task['id']);
                            $update_result = $this->db->update('task', $task);
                            
                            if ($update_result) {
                                $updated_count++;
                            } else {
                                $errors[] = array(
                                    'task_id' => $task['id'],
                                    'type' => 'update',
                                    'message' => $this->db->_error_message(),
                                    'error_code' => $this->db->_error_number()
                                );
                            }
                        } else {
                            // 任务不存在，执行插入
                            $insert_result = $this->db->insert('task', $task);
                            
                            if ($insert_result) {
                                $inserted_count++;
                            } else {
                                $errors[] = array(
                                    'task_id' => $task['id'],
                                    'type' => 'insert',
                                    'message' => $this->db->_error_message(),
                                    'error_code' => $this->db->_error_number()
                                );
                            }
                        }
                    } catch (Exception $task_e) {
                        $errors[] = array(
                            'task_id' => isset($task['id']) ? $task['id'] : 'unknown',
                            'type' => 'exception',
                            'message' => $task_e->getMessage(),
                            'trace' => $task_e->getTraceAsString()
                        );
                    }
                }
                
                $message = "批量操作完成: 更新了{$updated_count}个任务, 新增了{$inserted_count}个任务";
                $data = array(
                    'updated_count' => $updated_count,
                    'inserted_count' => $inserted_count,
                    'total_processed' => count($tasks)
                );
                
                if (!empty($errors)) {
                    $response = $this->create_response(2, 'partial_success', $message, $data, $errors);
                } else {
                    $response = $this->create_response(0, 'success', $message, $data);
                }
            }
        } catch (Exception $e) {
            $response = $this->create_response(500, 'error', '批量更新任务时发生错误', null, array(
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ));
        }
        
        $this->array_to_json($response);
    }
    
    public function updateOneTask()
    {
        try {
            if (empty($_POST['task'])) {
                $response = $this->create_response(400, 'error', '没有上传要更新的任务', null);
            } else {
                $task = $_POST['task'];
                $task['sync']=1;

                // 定义需要检查的字段数组
                $fieldsToCheck = ['start_date', 'end_date', 'internal_link', 'parent', 
                                 'gid', 'tid', 'icon', 'deleted', 'updated_device', 'areaid',
                                 'grandfather', 'num', 'haschild', 'allday'];

                // 遍历数组，将空字符串转换为null
                foreach ($fieldsToCheck as $field) {
                    if (isset($task[$field]) && $task[$field] === '') {
                        $task[$field] = null;
                    }
                }

                // 检查任务是否存在
                $this->db->where('id', $task['id']);
                $query = $this->db->get('task');
                
                if ($query->num_rows() > 0) {
                    // 任务存在，执行更新
                    $this->db->where('id', $task['id']);
                    $update_result = $this->db->update('task', $task);
                    
                    if ($update_result) {
                        $response = $this->create_response(0, 'success', '任务更新成功', array('task_id' => $task['id']));
                    } else {
                        $response = $this->create_response(3, 'update_failed', '任务更新失败', null, array(
                            'message' => $this->db->_error_message(),
                            'error_code' => $this->db->_error_number()
                        ));
                    }
                } else {
                    // 任务不存在，执行插入
                    $insert_result = $this->db->insert('task', $task);
                    
                    if ($insert_result) {
                        $insert_id = $this->db->insert_id();
                        $response = $this->create_response(0, 'success', '任务创建成功', array('task_id' => $insert_id));
                    } else {
                        $response = $this->create_response(4, 'insert_failed', '任务创建失败', null, array(
                            'message' => $this->db->_error_message(),
                            'error_code' => $this->db->_error_number()
                        ));
                    }
                }
            }
        } catch (Exception $e) {
            $response = $this->create_response(500, 'error', '更新任务时发生错误', null, array(
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ));
        }
        
        $this->array_to_json($response);
    }
}
    